package kr.ac.hufs.ice.cap.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;

import android.util.Log;

public class PageStreamer {

	int size;
	Argv argv[];
	String url;
	String servName;
	
	public void setRootURL(String servName) {
		this.servName = servName;
	}

	public PageStreamer() {
		argv = new Argv[1024];
		size = 0;
	}

	public void add(String key, String value) {

		try {
			argv[size++] = new Argv(key, java.net.URLEncoder.encode(new String(
					value.getBytes("UTF-8"))));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public String getKey(int index) {
		return argv[index].getKey();
	}

	public String getValue(int index) {
		return argv[index].getValue();
	}

	public String getArgv() {
		String result = "";
		for (int i = 0; i < size; i++) {
			if (i == size - 1 && i == 0) {
				result += "?" + argv[i].getKey() + "=" + argv[i].getValue();
			}
			else if (i == 0) {
				result += "?" + argv[i].getKey() + "=" + argv[i].getValue()
						+ "&";
			}
			else if (i == size - 1) {
				result += argv[i].getKey() + "=" + argv[i].getValue();
			}
			else {
				result += argv[i].getKey() + "=" + argv[i].getValue() + "&";
			}
		}
		return result;
	}

	public String getPageStream() {

		String url = servName + getArgv();

		Log.e("url is in getPageStream", url);

		StringBuffer sb = new StringBuffer(1024);

		java.io.BufferedReader in = null;

		try {
			String line = "";
			java.net.URL ocu = new java.net.URL(url);
			java.net.URLConnection con = ocu.openConnection();
			in = new java.io.BufferedReader(new java.io.InputStreamReader(
					con.getInputStream(), "UTF-8"));

			while ((line = in.readLine()) != null) {
				sb.append(line);
			}

		} catch (MalformedURLException e) {
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.e("pageSteam in getPageSteram", sb.toString());
		return sb.toString();	
	}
}

class Argv {

	private String key;
	private String value;

	public Argv(String key, String value) {
		this.key = key;
		this.value = value;
	}

	public String getKey() {
		return key;
	}

	public String getValue() {
		return value;
	}
}
